﻿using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

namespace Murry.DataStore.MongoDB
{
    /// <summary>
    /// Base class for all Mongo entities.
    /// </summary>
    public abstract class MongoPersist : IPersist
    {
        /// <summary>
        /// Standard constructor.
        /// </summary>
        /// <param name="database">Mongo Database Instance.</param>
        protected MongoPersist(MongoDatabase database)
        {
            Database = database;
        }

        /// <summary>
        /// Database instance.
        /// </summary>
        protected MongoDatabase Database;

        /// <summary>
        /// Unique Identifier.
        /// </summary>
        [BsonId]
        public string Id { get; set; }

        /// <summary>
        /// Add to DataStore.
        /// </summary>
        public virtual void Add()
        {
            var collection = Database.GetCollection(GetType(), GetType().Name);
            collection.Save(this);
        }

        /// <summary>
        /// Update in DataStore.
        /// </summary>
        public virtual void Update()
        {
            var collection = Database.GetCollection(GetType(), GetType().Name);
            collection.Save(this);
        }

        /// <summary>
        /// Delete from DataStore.
        /// </summary>
        public virtual void Delete()
        {
            var collection = Database.GetCollection(GetType(), GetType().Name);
            collection.Remove(Query<MongoPersist>.EQ(o => o.Id, Id));
        }
    }
}
